package com.fdl.service.security.impl;

import java.util.Date;

import org.acegisecurity.Authentication;
import org.acegisecurity.event.authentication.AbstractAuthenticationEvent;
import org.acegisecurity.event.authentication.AbstractAuthenticationFailureEvent;
import org.acegisecurity.event.authentication.InteractiveAuthenticationSuccessEvent;
import org.acegisecurity.ui.WebAuthenticationDetails;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

import com.fdl.dao.model.security.User;
import com.fdl.service.security.SecurityService;

/**
 * 认证监听
 * @project: hb-intra
 * @Date:2010-8-6
 * @version  1.0
 * @Company: 33e9
 * @author zhangYong.huang
 */
public class AuthenticationEventListener implements ApplicationListener {
	private static final Log log = LogFactory.getLog(AuthenticationEventListener.class);

	private SecurityService securityService;

	public void setSecurityService(SecurityService securityService) {
		this.securityService = securityService;
	}
	
	/**
	 * 认证成功后记录登陆信息
	 */
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof AbstractAuthenticationEvent) {

			AbstractAuthenticationEvent authEvent = (AbstractAuthenticationEvent) event;
			Authentication authentication = authEvent.getAuthentication();

			Object details = authentication.getDetails();
			String detailStr = (details instanceof WebAuthenticationDetails) ? ((WebAuthenticationDetails) details)
					.getRemoteAddress()
					: details.toString();

			if (event instanceof InteractiveAuthenticationSuccessEvent) {
				User user = ((User) authentication.getPrincipal());
				securityService.onSuccessLogin(user, detailStr);
				log.info(authentication.getName()+":登录成功");
			} else if (event instanceof AbstractAuthenticationFailureEvent) {
				log.error("用户名[" + authentication.getName() + "]登录失败",
						((AbstractAuthenticationFailureEvent) event).getException());
			}
		}
	}
}
